package util;

import java.sql.*;

public class JavaUtil1 {
    private static String driver="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://localhost:3306/library?useSSL=false&useUnicode=true&characterEncoding=utf-8";
    private static String username="root";
    private static String password="root";
    private static Connection con;//连接
    private static PreparedStatement ps;//预编译sql对象
    private static ResultSet rs;

    public static boolean getCon(){
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static int excuteupdate(String sql,Object[] o){
        int updateRows=0;
        if (getCon()==true){
            try {
                PreparedStatement ps=con.prepareStatement(sql);
                for (int i=0;i<o.length;i++){
                    ps.setObject(i+1,o[i]);
                }
                updateRows=ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return updateRows;
    }


    public static ResultSet excutequery(String sql,Object[] o){
        if (getCon()){
            try {
                ps=con.prepareStatement(sql);
                for (int i=0;i<o.length;i++){
                    ps.setObject(i+1,o[i]);
                }
                rs=ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }

    public static void close() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
